package practice;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class MyCalculator extends JFrame implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField Input;
	private boolean isNewNum = true;
	private double a = 0;
	private String s = null;

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				new MyCalculator();
			}
		});
	}

	public MyCalculator() {
		setSize(300, 280);
		setLocation(500, 150);
		setVisible(true);
		setTitle("My Calculator");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		JPanel top = new JPanel();
		add(top, BorderLayout.NORTH);
		Input = new JTextField();
		top.setLayout(new BorderLayout());
		top.add(Input);
		Input.setEnabled(false);
		Input.setDisabledTextColor(Color.DARK_GRAY);
		Input.setFont(new Font("黑体", Font.BOLD, 30));
		Input.setHorizontalAlignment(JTextField.RIGHT);
		Input.setText("0");
		JButton clear = new JButton("清除");
		top.add(clear, BorderLayout.EAST);
		clear.addActionListener(this);
		JPanel center = new JPanel();
		center.setLayout(new GridLayout(4, 4));
		add(center, BorderLayout.CENTER);
		String bn[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3",
				"×", "0", ".", "=", "÷", };
		for (String string : bn) {
			JButton botton = new JButton(string);
			center.add(botton);
			botton.addActionListener(this);
			botton.setFont(new Font("黑体", Font.BOLD, 20));
		}
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		String txt = arg0.getActionCommand();
		if (".0123456789".indexOf(txt) >= 0) {
			showNum(txt);
		} else if (txt.equals("清除")) {
			Input.setText("0");
			isNewNum = true;
			a = 0;
			s = null;
		} else {
			isNewNum = true;
			Suan(arg0.getActionCommand());
		}
	}

	private void Suan(String txt) {
		double b = Double.valueOf(Input.getText());
		if (s != null) {
			switch (s) {
			case "+":
				a += b;
				break;
			case "-":
				a -= b;
				break;
			case "×":
				a *= b;
				break;
			case "÷":
				a /= b;
				break;
			}
			Input.setText(String.valueOf(a));
		} else {
			a = b;
		}
		s = txt;
	}

	public void showNum(String txt) {
		if (isNewNum == true) 
			Input.setText("0");
			String ytxt = Input.getText();
			double ynum = Double.valueOf(ytxt);
			if (ynum == 0 && ytxt.indexOf(".") < 0) {
				if (txt.equals("."))
					Input.setText("0.");
				else {
					Input.setText(txt);
				}
			} else {
				if (ytxt.indexOf(".") < 0 || !txt.equals("."))
					Input.setText(ytxt + txt);
			}
			isNewNum = false;
		}
	}
